<?php


namespace Rabbitmq\Tool\RabbitMQTool;


use ErrorException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;

abstract class ConsumerBaseService
{
    /**
     * @var RabbitMQInstance
     */
    protected $instance;
    /**
     * AMQPExchange Name
     * @var string
     */
    protected $exchange = '';

    /**
     * AMQPExchange Type
     * @var string
     */
    protected $exchangeType = AMQPExchangeType::DIRECT;

    /**
     * AMQPQueue Name
     * @var string
     */
    protected $queue = '';

    /**
     * Consumer identifier
     * @var string
     */
    protected $consumerTag = '';

    /**
     * AMQPMessage Route Key
     * 路由键
     *
     * @var string
     */
    protected $routeKey = '';

    /**
     * @var bool
     */
    protected $autoDelete = false;

    /**
     * @var
     */
    protected $durable = true;

    /**
     * @var bool
     */
    protected $exclusive = false;

    /**
     * @var
     */
    protected $passive = false;

    protected $exchangePassive = false;

    protected $autoAck = false;

    public function __construct()
    {
        $this->instance = new RabbitMQInstance();
        $this->handle();
    }

    /**
     * 队列消费
     */
    public function handle()
    {
        try {
            $this->instance->setQueue($this->queue)
                ->setExchange($this->exchange)
                ->setExchangeType($this->exchangeType)
                ->setDurable($this->durable)
                ->setAutoDelete($this->autoDelete)
                ->setExchangePassive($this->exchangePassive)
                ->setQueuePassive($this->passive)
                ->setExclusive($this->exclusive)
                ->setAutoAck($this->autoAck)
                ->consume(function (AMQPMessage $message) {
                    $this->processMessage($message);
                });

        } catch (InvalidArgumentException | \Exception $exception) {
            Log::error('AMQPMessage consume error:' . $exception->getMessage());
        }
    }

    /**
     * Process Message
     *
     * @param AMQPMessage $message
     * @return mixed
     */
    private function processMessage(AMQPMessage $message)
    {
        $this->doProcess($message->getBody());
        $message->ack();
    }

    abstract protected function doProcess($param);
}
